// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <iostream>
#include <memory>
#include <string>

#include <nebula/io/stdio.h>
#include <nebula/ipc/reader.h>
#include <nebula/ipc/writer.h>
#include <nebula/core/record_batch.h>
#include <turbo/utility/status.h>

namespace nebula {
namespace ipc {

// Converts a stream from stdin to a file written to standard out.
// A typical usage would be:
// $ <program that produces streaming output> | stream-to-file > file.nebula
turbo::Status ConvertToFile() {
  io::StdinStream input;
  io::StdoutStream sink;

  IpcWriteOptions write_options;
  write_options.emit_dictionary_deltas = true;
  TURBO_MOVE_OR_RAISE(auto reader, RecordBatchStreamReader::open(&input));
  TURBO_MOVE_OR_RAISE(auto writer,
                        make_file_writer(&sink, reader->schema(), write_options));
  std::shared_ptr<RecordBatch> batch;
  while (true) {
    TURBO_MOVE_OR_RAISE(batch, reader->next());
    if (batch == nullptr) break;
    TURBO_RETURN_NOT_OK(writer->write_record_batch(*batch));
  }
  return writer->close();
}

}  // namespace ipc
}  // namespace nebula

int main(int argc, char** argv) {
  turbo::Status status = nebula::ipc::ConvertToFile();
  if (!status.ok()) {
    std::cerr << "Could not convert to file: " << status.to_string() << std::endl;
    return 1;
  }
  return 0;
}
